package com.sj.parksdk.fragment.carmanage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.ruffian.library.widget.helper.RBaseHelper;
import com.ruffian.library.widget.helper.RTextViewHelper;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.base.delegate.SimpleDelegateAdapter;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.fragment.certificate.FragmentCarCertificate;
import com.sj.parksdk.fragment.main.FragmentAddCar;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_Car;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.MRTextView.MRTextView;
import com.sj.parksdk.widget.MRTextView.VectorRTextViewHelper;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

@Page(name = "车辆管理", anim = CoreAnim.slide)
public class FragmentCarManage extends BaseFragment {


    @BindView(R2.id.recycler_car)
    RecyclerView recyclerCar;
    @BindView(R2.id.btn_add)
    SuperButton btnAdd;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;

    private SimpleDelegateAdapter<Data_Car> adapterCars;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_carmanage;
    }

    @Override
    protected void initViews() {
        initAdapter();
        queryCar();
    }

    private void initAdapter() {
        adapterCars = new SimpleDelegateAdapter<Data_Car>(R.layout.parksdk_adapter_cars, new LinearLayoutHelper()) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, Data_Car item) {
                holder.text(R.id.tv_name, item.getCarNo());
                holder.visible(R.id.rtv_state_certification, item.isVerified() ? View.VISIBLE : View.GONE);

                RTextView rtvStatePay = holder.findViewById(R.id.rtv_state_pay);
                RTextViewHelper rtvStatePayHelper = rtvStatePay.getHelper();
                rtvStatePay.setText(item.isAutoPay() ? "微信免密支付" : "绑定微信免密");
                rtvStatePayHelper.setTextColorNormal(item.isAutoPay() ? ResUtils.getColor(R.color.color_tip_green) : ResUtils.getColor(R.color.color_tip_red));
                rtvStatePayHelper.setBorderColorNormal(item.isAutoPay() ? ResUtils.getColor(R.color.color_tip_green) : ResUtils.getColor(R.color.color_tip_red));
                rtvStatePayHelper.setIconNormal(ResUtils.getDrawable(item.isAutoPay() ? R.mipmap.park_ic_weixin_pay : R.mipmap.park_icon_arrow_right_red));
                holder.text(R.id.tv_content, item.isVerified() ? "" : "认证后专享更多服务");

                RTextView rtvCarColor = holder.findViewById(R.id.rtv_car_color);
                RTextViewHelper rtvCarColorHeler = rtvCarColor.getHelper();
                RLinearLayout rllCarColor = holder.findViewById(R.id.rll_car_color);
                RBaseHelper rllCarColorHelper = rllCarColor.getHelper();
                int carColor = ResUtils.getColor(Dictionary.Car.PlateColor.PalteColorMap.get(StringUtils.isEmpty(item.getPlateColor()) ? Dictionary.Car.PlateColor.Unknow : item.getPlateColor()));
                rtvCarColorHeler.setBackgroundColorNormal(carColor);
                rtvCarColorHeler.setTextColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(item.getPlateColor()) ? R.color.color_3 : R.color.color_white));
                rtvCarColorHeler.setBorderWidthNormal(DensityUtils.dp2px(Dictionary.Car.PlateColor.White.equals(item.getPlateColor()) ? 1 : 0));
                rtvCarColor.setText(Dictionary.Car.PlateColor.PlateColorNameMap.get(item.getPlateColor()));
                rllCarColorHelper.setBorderColorNormal(Dictionary.Car.PlateColor.White.equals(item.getPlateColor()) ?ResUtils.getColor(R.color.color_3):carColor);

                holder.visible(R.id.rtv_car_certification, item.isVerified() ? View.GONE : View.VISIBLE);
                holder.click(R.id.rtv_car_certification, v -> gotoCarCetificat(item));

                holder.click(R.id.rtv_state_pay, v -> showAutopayFirstDialog(item));

                holder.click(R.id.iv_delete, v -> deleteCar(position, item));

                holder.click(R.id.rtv_park_record, v -> parkRecord(item));
            }
        };
        WidgetUtils.initRecyclerView(recyclerCar, DensityUtils.dp2px(10), ResUtils.getColor(R.color.color_cut_line));
        recyclerCar.setAdapter(adapterCars);
    }

    private void parkRecord(Data_Car item) {
        if(!item.isVerified())showCetificatFirstDialog(item);
        else gotoParkRecord(item);
    }

    private void showCetificatFirstDialog(Data_Car item) {
        new SweetAlertDialog(getContext(), SweetAlertDialog.NORMAL_CENTER_TITLE_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(100))
                .setContentText(ResUtils.getString(R.string.dialog_certificat_first))
                .setConfirmText(ResUtils.getString(R.string.dialog_button_goto_cetificat))
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        gotoCarCetificat(item);
                        sweetAlertDialog.dismiss();
                    }
                }).setCancelClickListener(null).show();
    }

    private void showAutopayFirstDialog(Data_Car item) {
        new SweetAlertDialog(getContext(), SweetAlertDialog.NORMAL_CENTER_TITLE_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(100))
                .setContentText(ResUtils.getString(R.string.dialog_autopay_first))
                .setConfirmText(ResUtils.getString(R.string.dialog_button_goto_bing))
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        gotoAutopayBind(item.getId());
                        sweetAlertDialog.dismiss();
                    }
                }).setCancelClickListener(null)
                .show();

    }

    private void gotoParkRecord(Data_Car item) {
        Bundle params = new Bundle();
        params.putLong(Extras.CAR_ID, item.getId());
        params.putString(Extras.CAR_NUMBER, item.getCarNo());
        params.putBoolean(Extras.CAR_IS_CETIFICAT, item.isVerified());
        params.putString(Extras.CAR_COLOR, item.getPlateColor());
        openPage(FragmentParkRecord.class, params);
    }

    //车辆认证
    private void gotoCarCetificat(Data_Car car) {
        PageOption.to(FragmentCarCertificate.class)
                .putLong(Extras.CAR_ID, car.getId())
                .putString(Extras.CAR_NUMBER, car.getCarNo())
                .putString(Extras.CAR_COLOR, car.getPlateColor())
                .putBoolean(Extras.CAR_IS_CETIFICAT, car.isVerified())
                .openForResult(this, Extras.REQUEST_CAR_CERTIFICATE);
    }

    //绑定微信支付
    private void gotoAutopayBind(long id) {

    }


    private void deleteCar(int position, Data_Car item) {
        if (item == null) return;
        showDeleteDialog(position, item.getId(), item.isAutoPay());
    }

    private void showDeleteDialog(int position, long id, boolean autopay) {
        if (!autopay) {
            new SweetAlertDialog(getContext(), SweetAlertDialog.WARNING_TYPE)
                    .setContentMinHeight(DensityUtils.dp2px(160))
                    .setContentText("确认删除该车辆?")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.setTitleGone(true).setContentText(null).setCancelable(false);
                            sDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                            deleteCarRequest(id, sDialog);
                        }
                    }).show();
            return;
        }


        SimpleDelegateAdapter adapterDeleteType = newDeleteTypeSelecteAdapter();
        LinearLayoutManager lm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        adapterDeleteType.refresh(Arrays.asList(ResUtils.getStringArray(R.array.park_delete_type)));

        new SweetAlertDialog(getContext(), SweetAlertDialog.RECYCLER_TYPE)
                .setTitleGone(true)
                .setContentText(null)
                .setRecyclerAdapter(adapterDeleteType, lm)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.setTitleGone(true).setContentText(null).setCancelable(false);
                        sDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                        //ToDo
                    }
                })
                .show();
    }

    private SimpleDelegateAdapter newDeleteTypeSelecteAdapter() {
        return new SimpleDelegateAdapter<String>(R.layout.parksdk_adapter_common_radio_list, new LinearLayoutHelper()) {

            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, String item) {
                MRTextView name = holder.findViewById(R.id.rtv_name);
                VectorRTextViewHelper nameHelper = name.getHelper();
                name.setText(item);
                if (position == getSelectPosition()) {
                    nameHelper.setIconNormal(ResUtils.getDrawable(R.drawable.park_ic_selected_common));
                } else {
                    nameHelper.setIconNormal(ResUtils.getDrawable(R.drawable.park_ic_unselected_common));
                }
                holder.click(R.id.ll_item, v -> setSelectPosition(position));
            }
        };
    }

    @SuppressLint("CheckResult")
    private void deleteCarRequest(long id, SweetAlertDialog sDialog) {
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .deleteCar(id))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
            @Override
            protected void onSuccess(CommonResult result) {
                deleteCarSuccess(result, sDialog);
            }

            @Override
            public void onError(ApiException e) {
                super.onError(e);
                if (sDialog != null) sDialog.dismiss();
            }
        });
    }

    private void deleteCarSuccess(CommonResult result, SweetAlertDialog sDialog) {
        if (result.getCode() != 200) XToastUtils.error(result.getMessage());
        sDialog.setTitleGone(true)
                .setContentText("删除成功")
                .setConfirmText("好的")
                .showCancelButton(false)
                .setCancelClickListener(null)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        queryCar();
                    }
                })
                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
    }

    @OnClick(R2.id.btn_add)
    public void onViewClicked() {
        PageOption.to(FragmentAddCar.class)
                .setRequestCode(Extras.REQUEST_CODE_ADD_CAR)
                .open(this);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (data == null) return;
        if (requestCode == Extras.REQUEST_CODE_ADD_CAR) addCarResult(data);
        else if (requestCode == Extras.REQUEST_CAR_CERTIFICATE) refreshCarList(data);
    }

    private void refreshCarList(Intent data) {
        boolean success = data.getBooleanExtra(Extras.BASE_SUCCESS_TYPE, false);
        if (success) queryCar();
    }

    private void addCarResult(Intent data) {
        boolean addCarSuccess = data.getBooleanExtra(Extras.CAR_ADD_CAR, false);
        if (addCarSuccess) queryCar();
    }

    private void queryCar() {
        llState.showLoading();
        new MGetRequest(MyNetApi.CAR_CARS)
                .user()
                .params(MyNetApi.PageParam.pageIndex, 1)
                .params(MyNetApi.PageParam.pageSize, 100)
                .execute(new TipRequestCallBack<Data_Car>() {
                    @Override
                    public void onSuccess(Data_Car response) throws Throwable {
                        queryCarsSuccess(response);
                    }

                    @Override
                    public void onError(ApiException e) {
                        llState.showError(e.getMessage(),null);
                    }
                });
    }

    private void queryCarsSuccess(Data_Car data) {
        if (data.getItems() == null) {
            llState.showCustom(emptyStatus());
            return;
        }
        if (data.getItems().size() == 0) llState.showCustom(emptyStatus());
        else llState.showContent();
        List<Data_Car> reversItems = data.getItems();
//        Collections.reverse(reversItems);
        adapterCars.refresh(reversItems);
    }


}
